package code.rocky.singleThreadExecution;

import java.util.concurrent.TimeUnit;

/**
 * 安全门
 */
public class SafeGate {

    private  int number;

    private String name;

    private String address;

    public synchronized void pass(User user) {
        this.number++;
        this.name = user.getName();
        // 休眠
        this.address = user.getAddress();
        check();
    }

    public  void pass1(User user) {
        this.number++;
        this.name = user.getName();
        // 休眠
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        this.address = user.getAddress();
        check();
    }

    @Override
    public synchronized String toString() {
        try {
            Thread.sleep(1000);

        } catch (InterruptedException e) {
        }
        return "No." + number  + ": "+ name + " : " + address;
    }

    /**
    @Override
    public  String toString() {
        return "No." + number  + ": "+ name + " : " + address;
    }
    */

    private void check() {
        if (name.charAt(0) != address.charAt(0)) {
            System.out.println("=== BROKEN ===" + toString());
        }
    }
}
